import 'package:color_dart/HexColor.dart';
import 'package:color_dart/RgbaColor.dart';
import "package:flutter/material.dart";
import 'package:im_flutter_sdk_example/components/a_button/index.dart';
import 'package:im_flutter_sdk_example/pages/domain/interest_item.dart';
import 'package:im_flutter_sdk_example/provider/tag_model.dart';
import 'package:im_flutter_sdk_example/utils/global.dart';
import 'package:im_flutter_sdk_example/utils/user_utils.dart';
import 'package:provider/provider.dart';
import 'widgets/select_swiper.dart';
import 'package:quiver/strings.dart';

class SelectInterest extends StatefulWidget {
  @override
  _SelectInterestState createState() => _SelectInterestState();
}

class _SelectInterestState extends State<SelectInterest> {
  List<InterestItem> selectTags = [];
  TextEditingController _textcontroller;

  @override
  Widget build(BuildContext context) {
    double height = G.screenHeight();
    double paddingTop = 80;
    double interestTagHeight = (height - paddingTop) / 2;

    return Scaffold(
      body: Container(
        color: Colors.white,
        child: ListView(
          scrollDirection: Axis.vertical,
          children: [
            Padding(
              padding: const EdgeInsets.all(0),
              child: Stack(
                children: [
                  Positioned(
                    child: Image.asset('lib/assets/images/doublequotation.png',
                        width: 40, height: 40),
                  ),
                  Positioned(
                    child: Padding(
                      padding: const EdgeInsets.fromLTRB(25, 66, 25, 0),
                      child: Text(
                        '请选择您感兴趣的领域',
                        style: TextStyle(
                            fontSize: 22,
                            fontWeight: FontWeight.bold,
                            decoration: TextDecoration.none,
                            color: rgba(51, 51, 51, 1)),
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Container(
              height: interestTagHeight,
              child: ListView(scrollDirection: Axis.vertical, children: [
                Container(
                  child: SelectSwiper(
                    height: interestTagHeight,
                    callBack: (selectIds) {
                      selectTags = selectIds;
                    },
                  ),
                ),
              ]),
            ),
            Container(
              margin: EdgeInsets.only(top: 50),
              padding: EdgeInsets.symmetric(horizontal: 25),
              child: Text(
                '自定义标签',
                style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    decoration: TextDecoration.none,
                    color: rgba(51, 51, 51, 1)),
              ),
            ),
            Column(
              children: [
                Wrap(
                  crossAxisAlignment: WrapCrossAlignment.center,
                  alignment: WrapAlignment.spaceBetween,
                  children: [
                    Container(
                      height: 55,
                      width: G.screenWidth() * 0.6,
                      margin: EdgeInsets.only(top: 20),
                      decoration: BoxDecoration(border: G.borderBottom()),
                      child: TextField(
                        controller: _textcontroller = TextEditingController(),
                        keyboardType: TextInputType.text,
                        decoration: InputDecoration(
                            counterText: "",
                            border: InputBorder.none,
                            hintText: '输入感兴趣的领域',
                            hintStyle: TextStyle(
                              color: rgba(163, 163, 163, 1),
                              fontSize: 16,
                            )),
                        onSubmitted: (e) {
                          if (isNotBlank(e)) {
                            _addUserTags([e.trim()]);
                            _textcontroller?.clear();
                          }
                        },
                      ),
                    ),
                    RaisedButton(
                      color: rgba(42, 125, 250, 1),
                      highlightColor: Colors.blue[400],
                      colorBrightness: Brightness.dark,
                      splashColor: Colors.grey,
                      onPressed: () {
                        String text = _textcontroller.text;
                        if (isNotBlank(text)) {
                          _addUserTags([text.trim()]);
                        }
                      },
                      child: Text('添加'),
                    )
                  ],
                ),
              ],
            ),
            _buildUserTags(),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20),
              child: AButton.normal(
                  width: double.infinity,
                  child: Text('确定'),
                  color: hex('#fff'),
                  bgColor: rgba(42, 125, 250, 1),
                  borderColor: rgba(136, 175, 213, 1),
                  onPressed: () => commit()),
            ),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20),
              margin: EdgeInsets.only(top: 25),
              child: AButton.normal(
                  width: double.infinity,
                  plain: true,
                  child: Text('跳过'),
                  color: rgba(136, 135, 135, 1),
                  bgColor: Colors.transparent,
                  onPressed: () => G.pushNamed('/index')),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      _loadUserTags();
    });
  }

  _loadUserTags() {
    TagProvider tagProvider = Provider.of<TagProvider>(context);
    tagProvider.loadMyTags();
  }

  _keyboardDown() {
    FocusScopeNode currentFocus = FocusScope.of(context);
    currentFocus.unfocus();
  }

  dispose() {
    super.dispose();
    _keyboardDown();
  }

  commit() async {
    List<String> tags = [];
    selectTags?.forEach((element) {
      tags.add(element.name);
    });
    _addUserTags(tags);
    // 保存 用户设置
    UserUtils.setTag();
    G.pushNamed('/index');
  }

  void _addUserTags(List<String> tags) async {
    // 去除 空字符
    var res = await G.req.user.addUserTag(tagIds: tags);
    _keyboardDown();
    Future.delayed(Duration(milliseconds: 5), () {
      _loadUserTags();
    });
  }

  _buildUserTags() {
    TagProvider tagProvider = Provider.of<TagProvider>(context);
    if (tagProvider.data == null) return Container();

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 20, horizontal: 25),
      child: Wrap(
        spacing: 8.0,
        runSpacing: 8.0,
        children: tagProvider.data.tags
            .map<Widget>((tag) => Chip(
                  backgroundColor: rgba(233, 242, 254, 1),
                  deleteIconColor: rgba(25, 109, 236, 1),
                  labelStyle:
                      TextStyle(color: rgba(25, 109, 236, 1), fontSize: 14),
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(4)),
                  label: Text('${tag.label}'),
                  onDeleted: () {
                    setState(() {
                      tagProvider.delTag(tag.label);
                    });
                  },
                ))
            .toList(),
      ),
    );
  }
}
